# -*- coding: utf-8 -*-
import logging

from django.contrib.auth import authenticate, login, logout, get_user_model
from django.contrib.auth.models import User
from rest_framework.decorators import action
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet

logger = logging.getLogger(__name__)


class UserView(GenericViewSet):
    authentication_classes = []
    permission_classes = []

    @action(methods=['post'], detail=False)
    def login(self, *args, **kwargs):
        logger.debug('login')
        try:
            username = self.request.data.get('username')
            password = self.request.data.get('password')
            # 验证账户和密码
            user: User = authenticate(request=self.request, username=username, password=password)
            if user is not None and user.is_active:
                logger.debug('authenticate success')
                # 存储session
                login(self.request, user)
                logger.debug('login success')

                # 生成token
                token = ''
                logger.debug('token success')

                return Response({
                    'code': 'login success',
                    'info': user.username,
                    'token': token
                })
            else:
                return Response({
                    'code': 'login failure',
                    'info': '登录失败',
                })
        except Exception as e:
            return Response({
                'code': 'Exception',
                'info': str(e),
            })

    @action(methods=['post'], detail=False)
    def logout(self, *args, **kwargs):
        logger.debug('logout')
        return Response({
            'code': 'logout success',
            'info': 'rest/user/login',
        })
